package com.rockwell.serial800;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.os.Bundle;
import android.app.Activity;
import android.hardware.usb.UsbManager;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialProber;
import com.hoho.android.usbserial.util.HexDump;
import com.hoho.android.usbserial.util.SerialInputOutputManager;

public class MainActivity extends Activity {
    private final String TAG = MainActivity.class.getSimpleName();

	UsbManager m_usbManager;
	UsbSerialDriver m_serialDevice;
	
    private final ExecutorService m_executor = Executors.newSingleThreadExecutor();

    private SerialInputOutputManager m_serialIoManager;

    private final SerialInputOutputManager.Listener m_listener =
            new SerialInputOutputManager.Listener() {

        @Override
        public void onRunError(Exception e) {
            Log.d(TAG, "Runner stopped.");
        }

        @Override
        public void onNewData(final byte[] data) {
            MainActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    MainActivity.this.updateReceivedData(data);
                }
            });
        }
    };
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
        m_usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
		
		setupSendButton();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	private void setupSendButton() {
		Button send = (Button)findViewById(R.id.send);
		
		send.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				sendData();
			}
			
		});
	}

	private void sendData() {
        m_serialDevice = UsbSerialProber.acquire(m_usbManager);
        Log.d(TAG, "Resumed, mSerialDevice=" + m_serialDevice);
        if (m_serialDevice == null) {
            //mTitleTextView.setText("No serial device.");
        } else {
            try {
            	m_serialDevice.open();
            } catch (IOException e) {
                Log.e(TAG, "Error setting up device: " + e.getMessage(), e);
                //mTitleTextView.setText("Error opening device: " + e.getMessage());
                try {
                	m_serialDevice.close();
                } catch (IOException e2) {
                    // Ignore.
                }
                m_serialDevice = null;
                return;
            }
            //mTitleTextView.setText("Serial device: " + m_serialDevice);
        }
        onDeviceStateChange();
	}
	
    private void stopIoManager() {
        if (m_serialIoManager != null) {
            Log.i(TAG, "Stopping io manager ..");
            m_serialIoManager.stop();
            m_serialIoManager = null;
        }
    }

    private void startIoManager() {
        if (m_serialDevice != null) {
            Log.i(TAG, "Starting io manager ..");
            m_serialIoManager = new SerialInputOutputManager(m_serialDevice, m_listener);
            m_executor.submit(m_serialIoManager);
        }
    }

    private void onDeviceStateChange() {
        stopIoManager();
        startIoManager();
    }

    private void updateReceivedData(byte[] data) {
        final String message = "Read " + data.length + " bytes: \n"
                + HexDump.dumpHexString(data) + "\n\n";
        //mDumpTextView.append(message);
        //mScrollView.smoothScrollTo(0, mDumpTextView.getBottom());
    }
}
